package com.bosssoft.hr.javase;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;

import java.util.List;

/**
 * @Description: 使用dom4j解析xml
 * @Author: WengYu
 * @CreateTime: 2022/05/13 19:07
 */
public class Dom4jPaser implements Paser {

    private boolean download(String url) {
        if ("".equals(url) || url == null){
            throw new RuntimeException("url不能为空");
        }
        return new HttpFileDownloader().download(url);
    }

    @Override
    public User[] parse(String url) {
        if (download(url)) {
            String path = url.trim().substring(url.lastIndexOf("/") + 1);

            SAXReader saxReader = new SAXReader();
            Document document = null;
            User[] users = null;
            try {
                saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
                // 读取文件
                document = saxReader.read(path);
                // 获取根节点 users
                Element root = document.getRootElement();
                // 获取所有user节点
                List<Element> childList = root.elements("user");

                if (!childList.isEmpty()){
                    // 初始化users数组
                    users = new User[childList.size()];
                    /**
                     * 遍历获取user节点下的子节点
                     * childList.get() 获取子节点
                     * element.attributeValue() 获取标签属性值
                     */
                    for (int i = 0; i < childList.size(); i++) {
                        Element element = childList.get(i);
                        // 获取子节点内容
                        for (Element names : element.elements()) {
                            users[i] = new User(Integer.valueOf(element.attributeValue("id")), names.getText());
                        }
                    }
                }
            } catch (DocumentException | SAXException e) {
                throw new RuntimeException(e);
            }
            return users;
        }
        return new User[]{};
    }

}
